<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin extends Controller_Tpl {
    //private $_data;

	public function before()
	{
		parent::before();
	}

	public function after()
	{
		parent::after();
	}
	
	public function action_users()
	{
		if ($this->request->method() === HTTP_Request::POST AND $this->request->post('action')=='createuser')
		{
					// Create a new user
			$post = $this->request->post();
			$user = ORM::factory('user')
				->values($post);
			
			if ($user->check())
			{
				// Saving login role and the one coming from dropdown menu
				$user->save();
				$user->add('roles', ORM::factory('role', array('name' => 'login')));
				$user->add('roles', ORM::factory('role', array('id' => $post['role'])));
			}
			//$this->_data[$this->_data['action']] = Model::factory('Admin')->get_users($this->_data['id']);
			//$this->_data['roles'] = Model::factory('Admin')->get_roles('roles');
			//echo Database::instance()->last_query;
			//$this->_data['createuser'] = '';//View::factory($this->_data['controller'].'/blocks/createuser',$this->_data);
		}
		elseif ($this->_data['type']=='short')
		{
			//$this->_data[$this->_data['action']] = Model::factory('Admin')->get_users($this->_data['id']);
			//$this->_data['roles'] = Model::factory('Admin')->get_roles('roles');
			//echo Database::instance()->last_query;
			//$this->_data['createuser'] = '';//View::factory($this->_data['controller'].'/blocks/createuser',$this->_data);			
		}
		else
		{
			$this->_data[$this->_data['action']] = Model::factory('Admin')->get_users($this->_data['id']);
			//$this->_data['roles'] = Model::factory('Admin')->get_roles('roles');
			//echo Database::instance()->last_query;
			//$this->_data['createuser'] = View::factory($this->_data['controller'].'/blocks/createuser',$this->_data);
		}

	}

	public function action_roles()
	{
		if ($this->request->method() === HTTP_Request::POST AND $this->request->post('action')=='createrole')
		{
			// Create a new user
			$post = $this->request->post();
			$user = ORM::factory('user')
				->values($post);
			
			if ($user->check())
			{
				// Saving login role and the one coming from dropdown menu
				$user->save();
				$user->add('roles', ORM::factory('role', array('name' => 'login')));
				$user->add('roles', ORM::factory('role', array('id' => $post['role'])));
			}	
		}
		else
		{
			$this->_data[$this->_data['action']] = Model::factory('Admin')->get_users($this->_data['id']);
			$this->_data['roles'] = Model::factory('Admin')->get_data('roles');
			//echo Database::instance()->last_query;
			//$this->_data['createrole'] = View::factory($this->_data['controller'].'/blocks/createrole',$this->_data);
		}
	}
		
	public function action_status()
	{
        if ($this->request->method() === HTTP_Request::POST)
        {
            $this->action_form();

        }
        else 
        {
        	$this->_data[$this->_data['action']] = Model::factory('Admin')->get_data($this->_data['action']);
        }		
	}

	public function action_additional()
	{
		$this->action_status();
	}

	public function action_subjects()
	{
		$this->action_status();
	}
	
	public function action_form()
	{
		if ($this->request->method() === HTTP_Request::POST)
		{
			$lead = Model::factory('Admin')->get_lead($this->_data['id']);
	
			switch ($this->request->post('action')) {
				case 'cal':
					if (empty($lead['clientsid']))
					{
						DB::insert('clients', array('lead_id', 'status_id', 'visit'))
							->values(array($lead['leadsid'], 1, $this->request->post('visit')))
							->execute();
					}
					else
					{
						DB::update('clients')
							->set(array('status_id'=>1,'visit'=>$this->request->post('visit')))
							->where('lead_id','=',$lead['leadsid'])
							->execute();
					}
				break;
				case 'card':
					if (empty($lead['clientsid']))
					{
						DB::insert('clients', array('lead_id', 'status_id', 'visit'))
							->values(array($lead['leadsid'], 1, $this->request->post('visit')))
							->execute();
					}
					else
					{
						DB::update('leads')
							->set(array('phone'=>$this->request->post('phone'),'name'=>$this->request->post('name'),'leadstext'=>$this->request->post('leadstext')))
							->where('leadsid','=',$lead['leadsid'])
							->execute();
					}
				break;
				case 'status':
				case 'additional':
				case 'subjects':
					Model::factory('Admin')->update_data($this->request->post());
				break;
			}
			//echo 'POST';
		}
		else
		{
			if (isset($this->_data['id']))
			{
				$this->_data['lead'] = DB::select()->from('leads')
					->join('clients','LEFT')
					->on('leads.leadsid', '=', 'clients.lead_id')
					->where('leads.leadsid','=',$this->_data['id'])
					->limit(1)
					->execute()
					->current();
					if (empty($this->_data['lead']['clientsid']))
					{
						DB::insert('clients', array('lead_id'))
							->values(array($this->_data['lead']['leadsid']))
							->execute();
					}
				$calendar = DB::select('visit',array(DB::expr('COUNT(`visit`)'),'count'))->from('clients')
					->where('status_id','=',1)
					->and_where('visit', 'BETWEEN', array(strtotime("Monday this week"),strtotime("Sunday")))
					->group_by('visit')
					->execute()
					->as_array();
				//echo Database::instance()->last_query;
				//print_r($this->_data['calendar']);
				foreach($calendar as &$row)
				{
					$this->_data['calendar'][$row['visit']] = $row['count'];
				}

			}
			//exit();

			$this->_data['worktime']['start'] = 9;
			$this->_data['worktime']['end'] = 20;
			//$this->_data['calendar'] = array();
			$this->_data['im'] = !empty($this->_data['lead']['visit'])?$this->_data['lead']['visit']:0;
		}
	}
	

	public function action_formroles()
	{
		//View::factory($this->_data['controller'].'/blocks/createrole',$this->_data);
		$this->_data['roles'] = Model::factory('Admin')->get_roles();
		$this->_data['role'] = Model::factory('Admin')->get_role($this->_data['id']);

	}

	public function action_formusers()
	{
		//View::factory($this->_data['controller'].'/blocks/createrole',$this->_data);
		$this->_data['roles'] = Model::factory('Admin')->get_roles();
		$this->_data['user'] = Model::factory('Admin')->get_user($this->_data['id']);
	}
	
} // End Admin